import { OnInit, Component, Output, EventEmitter, ViewChild } from '@angular/core';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { AcademyDTO } from 'src/app/project/model/icm/icm-base/academy/academy.dto';
import { AcademyService } from 'src/app/project/service/icm/icm-base/academy/academy.service';
import { FormBuilder, FormGroup, Validators, NgForm, FormControl, ValidationErrors } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { FormUtil } from '@shared/utils/form-util';

@Component({
  selector: 'app-academy-detail',
  templateUrl: './academy-detail.component.html',
  styles: [],
})
export class AcademyDetailComponent implements OnInit {
  constructor(private academyService: AcademyService, private fb: FormBuilder, private msg: NzMessageService) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required], [this.codeAsyncValidator]],
      name: ['', [Validators.required, Validators.pattern('[^ ]+')]],
      shortName: [''],
      showOrder: ['', [Validators.required]],
    });
  }

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<AcademyDTO>>();

  /**
   * form组件
   */
  @ViewChild('academyForm', { static: false })
  public academyForm: NgForm;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 学院编码是否已存在，true为已存在
   */
  isExist: boolean;

  /**
   * 学院信息
   */
  academy: AcademyDTO = {
    id: null,
    code: '',
    name: '',
    shortName: '',
    showOrder: 0,
  };

  /**
   * 校验配置名称
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      this.academyService.checkoutCodeIsExist(control.value).subscribe(data => {
        this.isExist = data.data;
      });
      setTimeout(() => {
        if (this.isExist) {
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 编辑/预览
   */
  preview() {
    // 编辑状态下isPreView为false，isReView为true
    this.isPreView = !this.isPreView;
  }

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.academyForm.form);
  }

  /**
   * 修改或新增学院信息
   * @param isPreView 是否预览
   * @param item 学院信息
   */
  edit(isPreView: boolean, item: AcademyDTO) {
    this.isPreView = isPreView;

    this.academy = this.initAcademy(item);
    this.isVisible = true;
  }

  /**
   * 初始化学院信息
   */
  initAcademy(item: AcademyDTO): AcademyDTO {
    return {
      id: item ? item.id : null,
      name: item ? item.name : '',
      code: item ? item.code : '',
      showOrder: item ? item.showOrder : 0,
      shortName: item ? item.shortName : '',
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.academy.code === '') {
      this.msg.error('学院编码必填');
      return false;
    }
    if (this.academy.name === '') {
      this.msg.error('学院名称必填');
      return false;
    }
    if (!this.academy.showOrder && this.academy.showOrder !== 0) {
      this.msg.error('显示顺序必填');
      return false;
    }
    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.academy.id) {
      // id为空，为新建
      this.academyService.create(this.academy).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.academyService.complete(this.academy.id, this.academy).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: AcademyDTO, operation: OperationType): void {
    this.loading = false;
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
    this.handleCancel();
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {}
}
